package com.example.a001.part33;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.a001.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etKey;
    private Button btnSearch;
    private ListView lv4Keys;
    private MyListViewAdapter myListViewAdapter;

    private static final long CLICK_TIME_INTERVAL = 500;
    private long lastClickTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main10);

        etKey = findViewById(R.id.etKey);
        btnSearch = findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(this);
        lv4Keys = findViewById(R.id.lv4Keys);

        myListViewAdapter = new MyListViewAdapter(this, new ArrayList<>());
        lv4Keys.setAdapter(myListViewAdapter);

        EventBus.getDefault().register(this);
    }

    private void searchKey() {
        String key = etKey.getText().toString().trim();

        if (key.isEmpty()) {
            Toast.makeText(this, "请输入搜索关键字", Toast.LENGTH_SHORT).show();
            return;
        }

        VolleySupport.getInstance().sendRequest4Get(
                "sug?",
                "code=utf-8&q=" + key,
                Result4TaobaoSug.class);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btnSearch) {
            if (isFastDoubleClick()) return;
            searchKey();
        }
    }

    private boolean isFastDoubleClick() {
        long currentClickTime = System.currentTimeMillis();
        long timeInterval = currentClickTime - lastClickTime;
        lastClickTime = currentClickTime;
        return timeInterval < CLICK_TIME_INTERVAL;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetTaobaoSug(Result4TaobaoSug result4TaobaoSug) {
        if (result4TaobaoSug != null && result4TaobaoSug.getResult() != null && !result4TaobaoSug.getResult().isEmpty()) {
            List<String> list4Sug = new ArrayList<>();
            for (List<String> list : result4TaobaoSug.getResult()) {
                if (!list.isEmpty()) {
                    list4Sug.add(list.get(0));
                }
            }
            myListViewAdapter.updateData(list4Sug);
        } else {
            Toast.makeText(this, "未找到相关结果", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}
